package com.example.appointment.common;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by LGM on 2015/12/2.
 */
public class Utils {
    /**
     * 复制图片
     *
     * @param mshowpicture
     */
    public static void copyimg(final ImageView mshowpicture) {
        //将ImageView中的图片转换成Bitmap
        new Thread() {
            @Override
            public void run() {
                super.run();
                mshowpicture.buildDrawingCache();

                Bitmap bitmap = mshowpicture.getDrawingCache();

//将Bitmap 转换成二进制，写入本地

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();
                File dir = new File(Environment.getExternalStorageDirectory() + "/FavoriteImage");
                if (!dir.isFile()) {
                    dir.mkdir();
                }
                File file = new File(dir, Math.random() * 1000000 + ".png");
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(byteArray, 0, byteArray.length);

                    fos.flush();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }.start();

    }

    public static String encryptMD5(String inputText, String algorithmName) {
        if (inputText == null || "".equals(inputText.trim())) {
            throw new IllegalArgumentException("请输入要加密的内容");
        }
        if (algorithmName == null || "".equals(algorithmName.trim())) {
            algorithmName = "md5";
        }
        String encryptText = null;
        try {
            MessageDigest m = MessageDigest.getInstance(algorithmName);
            m.update(inputText.getBytes("UTF-8"));
            byte s[] = m.digest();
            // m.digest(inputText.getBytes("UTF8"));
            return hex(s);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encryptText;
    }

    public static Bitmap getViewBitmap(View v) {
        if (v.getWidth() == 0 || v.getHeight() == 0)
            return null;
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);
        return b;
    }

    public static String getDateyyyyMMddHHmmss(Date date) {
        return getDateFormat(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 复制单个图片
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @return boolean
     */
    public static void copyFile(String oldPath) {
        File path = new File(Environment.getExternalStorageDirectory() + "/FavoriteImage");
        if (!path.exists()) {
            path.mkdirs();
        }
        String newPath = Environment.getExternalStorageDirectory() + "/FavoriteImage/" + Math.random() * 1000000 + ".jpg";
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
        }

    }

    public static String getDateFormat(Date date, String format) {
        DateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(date);
    }
//	public static Bitmap blur(Context context, Bitmap sentBitmap, int radius) {
//		final Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
//		final RenderScript rs = RenderScript.create(context);
//		final Allocation input = Allocation.createFromBitmap(rs, sentBitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
//		final Allocation output = Allocation.createTyped(rs, input.getType());
//		final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
//		script.setRadius(radius);
//		script.setInput(input);
//		script.forEach(output);
//		output.copyTo(bitmap);
//
//		sentBitmap.recycle();
//		rs.destroy();
//		input.destroy();
//		output.destroy();
//		script.destroy();
//
//		return bitmap;
//	}

    // 返回十六进制字符�?
    private static String hex(byte[] arr) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; ++i) {
            sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1,
                    3));
        }
        return sb.toString();
    }

    public static void showShortToast(Context context, String text) {
        try {
            Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void showAlertDialog(Context context, String title,
                                       String message, String positive, String negative,
                                       final PositiveListener pListener) {
        if (TextUtils.isEmpty(message)) {
            return;
        }
        // final Context fContext = context;
        // final String fMessage = message.replace("-","");
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setMessage(message);
        builder.setTitle(title);
        builder.setPositiveButton(positive, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // Main.this.finish();
                if (pListener == null) {
                    return;
                }
                pListener.OnPositiveClick();

            }
        });
        builder.setNegativeButton(negative, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    public interface PositiveListener {
        public void OnPositiveClick();
    }


    /**
     * 列表对话框
     *
     * @param context
     * @param names
     * @param listener
     */
    public static void showItemDialog(Context context, String title,
                                      String[] names, DialogInterface.OnClickListener listener) {
        if (names == null || names.length < 1) {
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setItems(names, listener);
        if (!TextUtils.isEmpty(title)) {
            builder.setTitle(title);
        }
        builder.show();
    }

    /**
     * 列表对话框
     *
     * @param context
     * @param names
     * @param listener
     */
    public static void showItemDialog(Context context, String[] names,
                                      DialogInterface.OnClickListener listener) {
        showItemDialog(context, null, names, listener);
    }


    /**
     * <p>
     * 获取一个当前正在运行任务中屏幕顶部的Activity ComponentName
     * </p>
     *
     * @return 返回屏幕顶部Activity ComponentName, 未获取到Activity则返回null
     */
    public static ComponentName getRunningTopActivity(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        // 获取当前正在运行的程序
        try {
            List<ActivityManager.RunningTaskInfo> runningTaskInfoList = am.getRunningTasks(1);
            ActivityManager.RunningTaskInfo taskInfo = runningTaskInfoList.get(0);
            return taskInfo.topActivity;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getVersionName(Context context) {
        try {
            String pkName = context.getApplicationContext().getPackageName();
            String versionName = context.getApplicationContext()
                    .getPackageManager().getPackageInfo(pkName, 0).versionName;
            return versionName;
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 掉此方法输入所要转换的时间输入例如（"2014-06-14-16-09-00"）返回时间戳
     *
     * @param time
     * @return
     */
    public static String Dataformat(String time, String formattype) {
        if (TextUtils.isEmpty(time)) {
            return null;
        }
        SimpleDateFormat sdr = new SimpleDateFormat(formattype,
                Locale.CHINA);
        Date date;
        String times = null;
        try {
            date = sdr.parse(time);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf;
//            times = stf.substring(0, 10);
//            Log.d("--444444---", times);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return times;
    }
}
